package com.hkts.naturalgas.base.controller;


import com.hkts.naturalgas.base.entity.CalcinationPurificationBleaching;
import com.hkts.naturalgas.utils.*;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.omg.CORBA.Object;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.alibaba.fastjson.JSON;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hkts.naturalgas.base.service.IRoastingPurifyWetElectricityService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hkts.naturalgas.base.entity.RoastingDesulphurizing;
import com.hkts.naturalgas.base.entity.RoastingPurificationBleaching;
import com.hkts.naturalgas.base.entity.RoastingPurifyWetElectricity;
import com.hkts.naturalgas.base.service.IRoastingPurifyWetElectricityService;
import com.hkts.naturalgas.utils.*;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.omg.CORBA.Object;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.text.ParseException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 焙烧净化湿电
 *
 * @author yck
 * @since 2021-05-31
 */
@RestController
@RequestMapping("/instrumentdata/roastingPurifyWetElectricity")
public class RoastingPurifyWetElectricityController {
    private final Logger logger = LoggerFactory.getLogger(RoastingPurifyWetElectricityController.class);

    @Autowired
    public IRoastingPurifyWetElectricityService iRoastingPurifyWetElectricityService;

    /**
     * 分页查询数据
     *
     * @param page                         分页信息
     * @param roastingPurifyWetElectricity 查询条件
     * @return
     */
    @ResponseBody
    @GetMapping("/getRoastingPurifyWetElectricityPageList")
    public Result<CustomPage> getHontUserList(Page<RoastingPurifyWetElectricity> page, RoastingPurifyWetElectricity roastingPurifyWetElectricity) {
        return ResultUtil.data(CustomPageUtils.getCustomPage(iRoastingPurifyWetElectricityService.selectPage(page, roastingPurifyWetElectricity)));
    }

    /**
     * 保存和修改公用的
     *
     * @param roastingPurifyWetElectricity 传递的实体
     * @return saveOrUpdate
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/roastingPurifyWetElectricitySave")
    public Result<Object> roastingPurifyWetElectricitySave(RoastingPurifyWetElectricity roastingPurifyWetElectricity) {
        iRoastingPurifyWetElectricityService.saveOrUpdate(roastingPurifyWetElectricity);
        return ResultUtil.success("保存成功");
    }

    /**
     * 根据id获取对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/roastingPurifyWetElectricityGetById")
    public Result<RoastingPurifyWetElectricity> roastingPurifyWetElectricityGetById(String id) {
        RoastingPurifyWetElectricity byId = iRoastingPurifyWetElectricityService.getById(id);
        return ResultUtil.data(byId);
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/roastingPurifyWetElectricityDelete")
    public Result<Object> hontUserDelete(String id) {
        iRoastingPurifyWetElectricityService.removeById(id);
        return ResultUtil.success("删除成功");
    }

    /**
     * 批量删除对象
     *
     * @param item 实体集合ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/roastingPurifyWetElectricityBatchDelete")
    public Result<Object> deleteBatchIds(String item) {
        List<String> ids = (List<String>) JSON.parse(item);
        iRoastingPurifyWetElectricityService.removeByIds(ids);
        return ResultUtil.success("删除成功");
    }

    /**
     * 功能描述:
     * 净化湿电数据处理 每小时内的数据转为每分钟
     *
     * @return:
     * @Author: 杨春科
     * @Date: 2021-06-08 10:26
     * @Description //TODO
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/dataHndler")
    @Transactional
    public Result dataHndler() throws ParseException {
        RoastingPurifyWetElectricity denitration = new RoastingPurifyWetElectricity();
        List<RoastingPurifyWetElectricity> roastingDusts = iRoastingPurifyWetElectricityService.selectList(denitration);
        List<String> collect = roastingDusts.stream().map(RoastingPurifyWetElectricity::getId).collect(Collectors.toList());
        System.out.println("删除数据");
        iRoastingPurifyWetElectricityService.deleteAll();
        for (int i = 0; i < roastingDusts.size(); i++) {
            if (i != roastingDusts.size() - 1) {
                LocalDateTime time = roastingDusts.get(i).getTime();
                System.out.println(time);
                Date date = Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
                List<LocalDateTime> allHourse = DataHandlerUtils.getAllHourse(date);
                //根据算法得到一个小时内的所有数据
                //煅烧A风机电流
                List<Float> bsjhSd2i2 = BezierPoint.getData(roastingDusts.get(i).getBsjhSd2i2(), roastingDusts.get(i + 1).getBsjhSd2i2());
                //煅烧A风机频率
                List<Float> bsjhSd2v2 = BezierPoint.getData(roastingDusts.get(i).getBsjhSd2v2(), roastingDusts.get(i + 1).getBsjhSd2v2());
                //煅烧B风机电流
                List<Float> bsjhSdi2 = BezierPoint.getData(roastingDusts.get(i).getBsjhSdi2(), roastingDusts.get(i + 1).getBsjhSdi2());
                //煅烧B风机频率
                List<Float> bsjhSdv2 = BezierPoint.getData(roastingDusts.get(i).getBsjhSdv2(), roastingDusts.get(i + 1).getBsjhSdv2());

                //进行循环处理
                List<RoastingPurifyWetElectricity> list = new ArrayList<RoastingPurifyWetElectricity>();
                for (int j = 0; j < bsjhSd2i2.size(); j++) {
                    if (j == 0) {
                        roastingDusts.get(i).setBsjhSdv2(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getBsjhSdv2()));
                        roastingDusts.get(i).setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
                        list.add(roastingDusts.get(i));
                    } else {
                        RoastingPurifyWetElectricity roastingPurifyWetElectricity = new RoastingPurifyWetElectricity();
                        roastingPurifyWetElectricity.setBsjhSdv2(bsjhSdv2.get(j));
                        roastingPurifyWetElectricity.setBsjhSdi2(bsjhSdi2.get(j));
                        roastingPurifyWetElectricity.setBsjhSd2v2(bsjhSd2v2.get(j));
                        roastingPurifyWetElectricity.setBsjhSd2i2(bsjhSd2i2.get(j));
                        roastingPurifyWetElectricity.setTime(allHourse.get(j));
                        roastingPurifyWetElectricity.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
                        list.add(roastingPurifyWetElectricity);
                    }

                }
                iRoastingPurifyWetElectricityService.saveBatch(list);
            } else {
                iRoastingPurifyWetElectricityService.save(roastingDusts.get(i));
            }
        }
        return ResultUtil.success("处理成功！");
    }
    /** 功能描述:
     *  遍历文件 将数据导入数据库
     * @return:
     * @Author: 杨春科
     * @Date: 2021-06-02 18:04
     * @Description //TODO
     */
    @PostMapping("/importByFiles")
    public Result<Object> importByFiles(String url) throws Exception {
        File file=new File(url);
        File[] files=file.listFiles();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(int i=0;i<files.length;i++){
            File nextfile=  files[i];
            System.out.println(nextfile.getName());
            HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(nextfile));
            HSSFSheet sheet = wb.getSheetAt(0);
            List<RoastingPurifyWetElectricity> list=new ArrayList<RoastingPurifyWetElectricity>(24);
            for (int j=3;j  >= 2&&j<27; j ++) {
                HSSFRow row1 = sheet.getRow(j);
                RoastingPurifyWetElectricity bleaching=new RoastingPurifyWetElectricity();
                bleaching.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
                System.out.println(row1.getCell(0).getDateCellValue());
                Date dateCellValue = row1.getCell(0).getDateCellValue();
                if(dateCellValue==null){
                    continue;
                }
                bleaching.setTime(dateCellValue.toInstant()
                        .atZone( ZoneId.systemDefault() )
                        .toLocalDateTime());
                //焙烧一电场二次电流
                bleaching.setBsjhSdi2((float)row1.getCell(2).getNumericCellValue());
                //焙烧一电场二次电压
                bleaching.setBsjhSdv2((float)row1.getCell(3).getNumericCellValue());
                //焙烧二电场二次电流
                bleaching.setBsjhSd2i2((float)row1.getCell(4).getNumericCellValue());
                //焙烧二电场二次电压
                bleaching.setBsjhSd2v2((float)row1.getCell(5).getNumericCellValue());
                list.add(bleaching);
            }
            iRoastingPurifyWetElectricityService.importByFiles(list);
        }

        return ResultUtil.success("成功");
    }
   //焙烧湿电数据导入
   @PostMapping("/importData")
   @ResponseBody
   @Transactional
   public Result<Object> importData(String url) throws Exception {
       File file=new File(url);
       SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

       HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
       HSSFSheet sheet = wb.getSheetAt(0);
       List<RoastingPurifyWetElectricity> list=new ArrayList<RoastingPurifyWetElectricity>(2000);
       for (int j=1;j  >= 1&&j<=sheet.getLastRowNum(); j ++) {
           HSSFRow row1 = sheet.getRow(j);
           RoastingPurifyWetElectricity lectricity=new RoastingPurifyWetElectricity();
           lectricity.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
           Date dateCellValue = row1.getCell(0).getDateCellValue();
           QueryWrapper<RoastingPurifyWetElectricity> query = Wrappers.query();
           //根据时间查询对象
           System.out.println(dateCellValue);
           lectricity.setTime(dateCellValue.toInstant()
                   .atZone( ZoneId.systemDefault() )
                   .toLocalDateTime());
           //焙烧湿电数据导入
           row1.getCell(1).setCellType(CellType.STRING);
           lectricity.setBsjhSdi2(Float.parseFloat (row1.getCell(1).getStringCellValue()));
           row1.getCell(2).setCellType(CellType.STRING);
           lectricity.setBsjhSdv2(Float.parseFloat (row1.getCell(2).getStringCellValue()));
           row1.getCell(3).setCellType(CellType.STRING);
           lectricity.setBsjhSd2i2(Float.parseFloat (row1.getCell(3).getStringCellValue()));
           row1.getCell(4).setCellType(CellType.STRING);
           lectricity.setBsjhSd2v2(Float.parseFloat (row1.getCell(4).getStringCellValue()));
           list.add(lectricity);
       }
       iRoastingPurifyWetElectricityService.saveBatch(list);
       return ResultUtil.success("成功");
   }

    /** 功能描述:
    *[url]
    * @return: com.hkts.naturalgas.utils.Result<org.omg.CORBA.Object>
    * @Author: 杨春科
    * @Date: 2021-06-15 15:57
    * @Description //TODO 根据导入内容修改会插入数据
    */
    @PostMapping("/importDataUpdate")
    @ResponseBody
    @Transactional
    public Result<Object> importDataUpdate(String url) throws Exception {
        File file=new File(url);
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
        HSSFSheet sheet = wb.getSheetAt(0);
        for (int j=1;j  >= 1&&j<=sheet.getLastRowNum(); j ++) {
            HSSFRow row1 = sheet.getRow(j);
            String date = row1.getCell(0).getStringCellValue();
            String time = row1.getCell(1).getStringCellValue();
            Date parse = format.parse("20" + date + " " + time);
            QueryWrapper<RoastingPurifyWetElectricity> query = Wrappers.query();
            query.eq(RoastingPurifyWetElectricity.TIME,parse.toInstant()
                    .atZone( ZoneId.systemDefault() )
                    .toLocalDateTime());
            RoastingPurifyWetElectricity lectricity = iRoastingPurifyWetElectricityService.getOne(query);
            if(lectricity==null){
               lectricity=new RoastingPurifyWetElectricity();
                lectricity.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
                Date dateCellValue = row1.getCell(0).getDateCellValue();
                lectricity.setTime(dateCellValue.toInstant()
                        .atZone( ZoneId.systemDefault() )
                        .toLocalDateTime());
            }
            //焙烧湿电数据导入
            row1.getCell(1).setCellType(CellType.STRING);
            lectricity.setBsjhSdi2(Float.parseFloat (row1.getCell(1).getStringCellValue()));
            row1.getCell(2).setCellType(CellType.STRING);
            lectricity.setBsjhSdv2(Float.parseFloat (row1.getCell(2).getStringCellValue()));
            row1.getCell(3).setCellType(CellType.STRING);
            lectricity.setBsjhSd2i2(Float.parseFloat (row1.getCell(3).getStringCellValue()));
            row1.getCell(4).setCellType(CellType.STRING);
            lectricity.setBsjhSd2v2(Float.parseFloat (row1.getCell(4).getStringCellValue()));
            iRoastingPurifyWetElectricityService.saveOrUpdate(lectricity);
        }
        return ResultUtil.success("成功");
    }

    /** 功能描述:
     *根据时间将数据补全 所有值全为0
     * @return:
     * @Author: 杨春科
     * @Date: 2021-06-17 10:49
     * @Description //TODO
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/addData")
    @Transactional
    public Result<java.lang.Object> addData( String beginDate, String endDate) throws ParseException {
        List<LocalDateTime> allMinites = DataHandlerUtils.getAllMinites(beginDate, endDate);
        List<RoastingPurifyWetElectricity> electricity =new ArrayList<RoastingPurifyWetElectricity>();
        for(int i=0;i<allMinites.size();i++){
            RoastingPurifyWetElectricity den=new RoastingPurifyWetElectricity();
            den.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
            den.setTime(allMinites.get(i));
            den.setBsjhSd2i2(0f);
            den.setBsjhSdv2(0f);
            den.setBsjhSdi2(0f);
            den.setBsjhSd2v2(0f);
            electricity.add(den);
        }
        iRoastingPurifyWetElectricityService.saveBatch(electricity);
        return ResultUtil.success("处理成功！");
    }

    /**
     * 功能描述:
     * 数据分割
     *
     * @return:
     * @Author: 杨春科
     * @Date: 2021-06-10 11:26
     * @Description //TODO
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/divisionData")
    @Transactional
    public Result<java.lang.Object> divisionData() throws Exception {
        RoastingPurifyWetElectricity den=new RoastingPurifyWetElectricity();
        List<RoastingPurifyWetElectricity> roastingDesulphurizings = iRoastingPurifyWetElectricityService.selectList(den);
       iRoastingPurifyWetElectricityService.deleteAll();
        for (int i = 0; i < roastingDesulphurizings.size(); i++) {
            if (i != roastingDesulphurizings.size() - 1) {
                LocalDateTime time = roastingDesulphurizings.get(i).getTime();
                System.out.println(time);
                Date date = Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
                List<LocalDateTime> allHourse = DataHandlerUtils.getAllHourse(date);
                List<RoastingPurifyWetElectricity> list = new ArrayList<>();
                //so2
                List<Float> dataSdi2 = DataHandlerUtils.getHandlerData(roastingDesulphurizings.get(i).getBsjhSdi2(), roastingDesulphurizings.get(i + 1).getBsjhSdi2());
                List<Float> dataSd2i2 = DataHandlerUtils.getHandlerData(roastingDesulphurizings.get(i).getBsjhSd2i2(), roastingDesulphurizings.get(i + 1).getBsjhSd2i2());
                List<Float> dataSd2v2 = DataHandlerUtils.getHandlerData(roastingDesulphurizings.get(i).getBsjhSdv2(), roastingDesulphurizings.get(i + 1).getBsjhSd2v2());
                List<Float> dataSdv2 = DataHandlerUtils.getHandlerData(roastingDesulphurizings.get(i).getBsjhSdv2(), roastingDesulphurizings.get(i + 1).getBsjhSdv2());
                //nox

                for (int j = 0; j < allHourse.size(); j++) {
                    if (j == 0) {
                        RoastingPurifyWetElectricity roastingPurifyWetElectricity = roastingDesulphurizings.get(i);
                        roastingPurifyWetElectricity.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
                        list.add(roastingPurifyWetElectricity);
                    } else {
                        //
                        RoastingPurifyWetElectricity electricity = new RoastingPurifyWetElectricity();
                        electricity.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
                        electricity.setTime(allHourse.get(j));
                        electricity.setBsjhSd2v2(dataSd2v2.get(j));
                        electricity.setBsjhSdi2(dataSdi2.get(j));
                        electricity.setBsjhSdv2(dataSdv2.get(j));
                        electricity.setBsjhSd2i2(dataSd2i2.get(j));
                        list.add(electricity);
                    }
                }
               iRoastingPurifyWetElectricityService.saveBatch(list);
            } else {
                roastingDesulphurizings.get(i).setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
               iRoastingPurifyWetElectricityService.save(roastingDesulphurizings.get(i));
            }
        }
        return ResultUtil.success("处理成功！");
    }

}
